package com.csu.csumall.controller.frontend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.User;
import com.csu.csumall.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import static com.csu.csumall.common.Constant.MIN_PASSWORD_LENGTH;
import static com.csu.csumall.common.Constant.ORIGIN;

@Slf4j
@RestController
@RequestMapping(value = "/api/user")
@CrossOrigin(origins = ORIGIN)
public class UserController {

    private final IUserService userService;
    private final PasswordEncoder passwordEncoder;

    @Autowired
    public UserController(IUserService userService, PasswordEncoder passwordEncoder) {
        this.userService = userService;
        this.passwordEncoder = passwordEncoder;
    }

    @PostMapping(value = "register", consumes = "application/json", produces = "application/json")
    public UniformResponse processRegistration(@RequestBody User user) {
        if (! userService.isUnusedUsername(user.getUsername())) {
            return UniformResponse.createForError("用户名已存在");
        } else if (! userService.isUnusedPhone(user.getPhone())) {
            return UniformResponse.createForError("手机号已存在");
        } else if (! userService.isUnusedEmail(user.getEmail())) {
            return UniformResponse.createForError("邮箱已存在");
        } else {
            String encodedPassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodedPassword);
            user.setCreateAndUpdateTime();
            user.setRole(0);
            userService.save(user);
//            return UniformResponse.createForSuccess("注册成功", user.clearSecretFiled());
            return UniformResponse.createForSuccess("注册成功", user);
        }
    }

    @GetMapping("check_valid")
    public UniformResponse checkValid(@RequestParam("str") String queryStr,
                                      @RequestParam("type") String type) {
        switch (type) {
            case "username":
                if (userService.isUnusedUsername(queryStr)) {
                    return UniformResponse.createForSuccess("用户名可用");
                } else {
                    return UniformResponse.createForError("用户名已存在");
                }
            case "phone":
                if (userService.isUnusedPhone(queryStr)) {
                    return UniformResponse.createForSuccess("手机号可用");
                } else {
                    return UniformResponse.createForError("手机号已存在");
                }
            case "email":
                if (userService.isUnusedEmail(queryStr)) {
                    return UniformResponse.createForSuccess("手机号可用");
                } else {
                    return UniformResponse.createForError("手机号已存在");
                }
            default:
                return UniformResponse.createForError("查询type有误");
        }
    }

    @GetMapping("get_user_info")
    public UniformResponse getUserInfo(@AuthenticationPrincipal User user) {
        if (user == null) {
            return UniformResponse.createForError("用户未登录或过期,无法获取当前用户信息");
        } else {
//            return UniformResponse.createForSuccess(user.clearSecretFiled());
            return UniformResponse.createForSuccess(user);
        }
    }

    @GetMapping("forget_get_question")
    public UniformResponse getQuestion(@RequestParam("queryStr") String queryStr,
                                       @RequestParam("type") String type) {

        User user = null;
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();

        switch (type) {
            case "username":
                queryWrapper.eq("username", queryStr).ne("status", ItemStatus.DISABLE.getValue());
                user = userService.getOne(queryWrapper);
                if (user != null) {
                    return UniformResponse.createForSuccess(user.getQuestion());
                } else {
                    return UniformResponse.createForError("用户名不存在");
                }
            case "phone":
                queryWrapper.eq("phone", queryStr).ne("status", ItemStatus.DISABLE.getValue());
                user = userService.getOne(queryWrapper);
                if (user != null) {
                    return UniformResponse.createForSuccess(user.getQuestion());
                } else {
                    return UniformResponse.createForError("手机号不存在");
                }
            case "email":
                queryWrapper.eq("email", queryStr).ne("status", ItemStatus.DISABLE.getValue());
                user = userService.getOne(queryWrapper);
                if (user != null) {
                    return UniformResponse.createForSuccess(user.getQuestion());
                } else {
                    return UniformResponse.createForError("邮箱不存在");
                }
            default:
                return UniformResponse.createForError("查询type有误");
        }
    }

    @PostMapping(value = "forget_check_answer", consumes = "application/json", produces = "application/json")
    public UniformResponse validatePasswordProtection(@RequestBody Map map, HttpSession httpSession) {

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", (String) map.get("username"))
                .eq("question", (String) map.get("question"))
                .eq("answer", (String) map.get("answer"))
                .ne("status", ItemStatus.DISABLE.getValue());
        int rows = userService.count(queryWrapper);
        if(rows == 0) {
            return UniformResponse.createForError("密保答案不正确");
        } else {
            User user = userService.getOne(queryWrapper);
            String forgetPasswordToken = UUID.randomUUID().toString();
            httpSession.setAttribute("forgetPasswordToken", forgetPasswordToken);
            httpSession.setAttribute("forgetUseId",  user.getId());
            Map<String, String> result = new HashMap<>();
            result.put("token", forgetPasswordToken);
            return UniformResponse.createForSuccess(result);
        }

    }

    @PostMapping(value = "forget_reset_password", consumes = "application/json", produces = "application/json")
    public UniformResponse restPassword(@RequestBody Map map, HttpSession httpSession) {
        String newPassword = (String) map.get("newPassword");
        if ((String) map.get("forgetPasswordToken") == null) {
            return UniformResponse.createForError("token为空");

        } else if (! ((String) map.get("forgetPasswordToken")).equals((String) httpSession.getAttribute("forgetPasswordToken"))) {
            return UniformResponse.createForError("token错误或过期");
        } else if (newPassword == null) {
            return UniformResponse.createForError("token错误或过期");
        } else if (newPassword.length() < MIN_PASSWORD_LENGTH) {
            return UniformResponse.createForError("密码最低" + MIN_PASSWORD_LENGTH + "位数");
        } else {
            User user = new User();
            user.setId((Integer) httpSession.getAttribute("forgetUseId"));
            user.setPassword(passwordEncoder.encode((String) map.get("newPassword")));
            user.setUpdateTime();
            userService.updateById(user);
            return UniformResponse.createForSuccess();
        }
    }

    @PostMapping(value = "reset_password", consumes = "application/json", produces = "application/json")
    public UniformResponse resetPasswordAtLoginStatus(@RequestBody Map map, @AuthenticationPrincipal User user) {
        String oldPassword = (String) map.get("oldPassword");
        String newPassword = (String) map.get("newPassword");
        if (user == null) {
            return UniformResponse.createForError("未登录");
        } else if (! passwordEncoder.matches(oldPassword, user.getPassword())) {
            return UniformResponse.createForError("旧密码错误");
        } else if (newPassword.length() < MIN_PASSWORD_LENGTH) {
            return UniformResponse.createForError("密码最低" + MIN_PASSWORD_LENGTH + "位数");
        } else {
            user.setPassword(passwordEncoder.encode(newPassword));
            user.setUpdateTime();
            userService.updateById(user);
            return UniformResponse.createForSuccess();
        }
    }

    @PostMapping(value = "update_information", consumes = "application/json", produces = "application/json")
    public UniformResponse updateInfoAtLoginStatus(@RequestBody Map map, @AuthenticationPrincipal User user) {
        if (user == null) {
            return UniformResponse.createForError("未登录");
        } else {
            boolean updateFlag = false;
            String phone = (String) map.get("phone");
            String email = (String) map.get("email");
            String question = (String) map.get("question");
            String answer = (String) map.get("answer");
            if (phone != null) {
                user.setPhone(phone);
                updateFlag = true;
            }
            if (email != null) {
                user.setEmail(email);
                updateFlag = true;
            }
            if (question != null) {
                user.setQuestion(question);
                updateFlag = true;
            }
            if (answer != null) {
                user.setAnswer(answer);
                updateFlag = true;
            }
            if (updateFlag) {
                user.setUpdateTime();
                userService.updateById(user);
                return UniformResponse.createForSuccess(user);
            } else {
                return UniformResponse.createForError("未传递新信息");
            }
        }

    }

    @GetMapping(value = "get_information")
    public UniformResponse getDetailInformationAtLoginStatus(@AuthenticationPrincipal User user) {
        if (user == null) {
            return UniformResponse.createForForceLogin("用户未登录，无法获取当前用户信息，强制登录");
        } else {
            Map<String, Object> result = new HashMap<>();
            result.put("id", user.getId());
            result.put("username", user.getUsername());
            result.put("email", user.getEmail());
            result.put("phone", user.getPhone());
            result.put("role", user.getRole());
            result.put("createTime", user.getCreateTime());
            result.put("UpdateTime", user.getUpdateTime());
            return UniformResponse.createForSuccess(result);
        }
    }



}
